package main

import (
	"flag"
	"fmt"
	"runtime"
	"time"

	"github.com/spf13/viper"
)

type Config struct {
	Base        BaseConf      `mapstructure:"base"`
	LogicConfig LogicConf     `mapstructure:"logicConfig"`
	Websocket   WebsocketConf `mapstructure:"websocket"`
	Bucket      BucketConf    `mapstructure:"bucket"`
}

// BaseConf 基础的配置信息
type BaseConf struct {
	Pidfile         string `mapstructure:"pidfile"`
	MaxProc         int
	PprofBind       string `mapstructure:"pprofBind"` // 性能监控的域名端口
	Logfile         string `mapstructure:"logfile"`   // log 文件
	rpcAddr         string `mapstructure:"RPCAddr"`
	WriteWait       time.Duration
	PongWait        time.Duration
	PingPeriod      time.Duration
	MaxMessageSize  int
	ReadBufferSize  int
	WriteBufferSize int
	BroadcastSize   int
	ServerId        int32 `mapstructure:"serverId"`
}

type LogicConf struct {
	Addr string `mapstructure:"addr"` // rpc comet层的配置
}

type BucketConf struct {
	Num           int    `mapstructure:"num"`
	Channel       int    `mapstructure:"channel"`
	Room          int    `mapstructure:"room"`
	SvrProto      int    `mapstructure:"svrProto"`
	RoutineAmount uint64 `mapstructure:"routineAmount"`
	RoutineSize   int    `mapstructure:"routineSize"`
}

type WebsocketConf struct {
	Bind string `mapstructure:"bind"` // 性能监控的域名端口
}

var (
	conf     *Config
	confPath string
)

func init() {
	flag.StringVar(&confPath, "d", "./comet/", " set logic config file path")
}

func InitConfig() (err error) {
	conf = NewConfig()
	viper.SetConfigName("comet")
	viper.SetConfigType("toml")
	viper.AddConfigPath(confPath)
	if err = viper.ReadInConfig(); err != nil {
		return err
	}
	if err = viper.Unmarshal(&conf); err != nil {
		panic(fmt.Errorf("unable to decode into struct：  %s \n", err))
	}
	return
}

func NewConfig() *Config {
	return &Config{
		Base: BaseConf{
			Pidfile:         "/tmp/comet.pid",
			Logfile:         "/Users/AT/go/src/im/logs/comet/comet.log",
			MaxProc:         runtime.NumCPU(),
			rpcAddr:         "tcp@localhost:6912",
			PprofBind:       "localhost:7911",
			WriteWait:       10 * time.Second,
			PongWait:        60 * time.Second,
			PingPeriod:      54 * time.Second,
			MaxMessageSize:  512,
			ReadBufferSize:  1024,
			WriteBufferSize: 1024,
			BroadcastSize:   512,
		},
		LogicConfig: LogicConf{
			Addr: "tpc@localhost:6923",
		},
		Bucket: BucketConf{
			Num:           256,
			Channel:       1024,
			Room:          1024,
			SvrProto:      80,
			RoutineAmount: 32,
			RoutineSize:   20,
		},
		Websocket: WebsocketConf{
			Bind: ":6911",
		},
	}
}
